package middlewares

import (
	"crypto/rand"
	"crypto/rsa"
	"github.com/dgrijalva/jwt-go"
	"log"
	"sync"
)

const (
	//默认过期时间900s，即15min
	DefaultEXP = 90
)

type JWTManager struct {
	key *rsa.PrivateKey
	mux sync.Mutex
}

func NewJWTManager() *JWTManager {
	return &JWTManager{
		key: nil,
		mux: sync.Mutex{},
	}
}

//初始化JWT管理
func (j *JWTManager) Init() {
	log.Print("Generating JWT signing key")
	j.mux.Lock()
	defer j.mux.Unlock()

	if j.key != nil {
		return
	}
	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		log.Fatal("Generating JWT signing key err", err)
	}
	j.key = privateKey
}

//生成jwt,使用RS256来签名
func (j *JWTManager) Generate(claims jwt.Claims) (string, error) {
	j.mux.Lock()
	defer j.mux.Unlock()
	token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
	return token.SignedString(j.key)
}

//对jwt进行解析和校验
func (j *JWTManager) Parse(tokenString string) (*jwt.Token, error) {
	j.mux.Lock()
	defer j.mux.Unlock()
	token, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
		return &j.key.PublicKey, nil
	})
	if err != nil {
		return nil, err
	}
	return token, nil
}
